package generics;

/**
 * Created with IntelliJ IDEA
 * Description:范型的上界
 * User：chenshu
 * Date：2023-10-26
 * Time：21:04
 */
//写一个泛型类，类中有个方法，求数组的最大值
class Alg<T extends Comparable<T>> {
    //T被擦除成了Object，也就没有继承Comparable接口
    //因此要定下泛式的上界-》也就是接收的引用必须实现Comparable接口
    public T findMax(T[] arr) {
        T max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (max.compareTo(arr[i]) < 0) {
                max = arr[i];
            }
        }
        return max;
    }
}

class Student implements Comparable<Student>{
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }
}

public class TestDemo2 {
    public static void main(String[] args) {
        Alg<Integer> alg = new Alg<>();
        Integer[] array = {1,5,3,21,8,19};
        Integer max = alg.findMax(array);
        System.out.println(max);

        Alg<Student> alg2 = new Alg<>();
        Student[] students = new Student[3];
        students[0] = new Student("s1", 20);
        students[1] = new Student("s2", 18);
        students[2] = new Student("s3", 15);
        Student s = alg2.findMax(students);
        System.out.println(s);
    }
}
